//
//  DolpProgressView.m
//  iOS-Learning-Demo
//
//  Created by yuan xiaodong on 2022/1/5.
//  Copyright © 2022 yuan. All rights reserved.
//

#import "DolpProgressView.h"

@interface DolpProgressView ()

@property (nonatomic, strong) CAShapeLayer *progressLayer;
@property (nonatomic, strong) CAShapeLayer *backgroundLayer;

@property (nonatomic, strong) UILabel *progressLabel;

@end

@implementation DolpProgressView

- (instancetype)init {
    self = [super init];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        
        _progressLayer = [CAShapeLayer layer];
        _progressLayer.fillColor = [[UIColor clearColor] CGColor];
        _progressLayer.strokeColor = [self.frontColor CGColor];
        _progressLayer.opacity = 1;
        _progressLayer.lineCap = kCALineCapRound;
        _progressLayer.lineWidth = 5;
        
        _backgroundLayer = [CAShapeLayer layer];
        _backgroundLayer.fillColor = [[UIColor clearColor] CGColor];
        _backgroundLayer.strokeColor = [self.backColor CGColor];
        _backgroundLayer.opacity = 1;
        _backgroundLayer.lineCap = kCALineCapRound;
        _backgroundLayer.lineWidth = 5;
        
        [self addSubview:self.progressLabel];
        
        self.progress = 0;
    }
    return self;
}

- (UIColor *)frontColor{
    return [UIColor redColor];
}

- (UIColor *)backColor{
    return [UIColor blueColor];
}

- (void)drawRect:(CGRect)rect {
    CGPoint center = CGPointMake(rect.size.width / 2, rect.size.height / 2);
    CGFloat radius = rect.size.width / 2;
    CGFloat startA = - M_PI_2;
    CGFloat endA = - M_PI_2 + M_PI * 2 * _progress;
    
    CGFloat endB = - M_PI_2 + M_PI * 2 ;
    
    _backgroundLayer.frame = self.bounds;
    UIBezierPath *backPath = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endB clockwise:YES];
    _backgroundLayer.path = [backPath CGPath];
    
    [_backgroundLayer removeFromSuperlayer];
    [self.layer addSublayer:_backgroundLayer];
    
    _progressLayer.frame = self.bounds;
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];
    _progressLayer.path = [path CGPath];
    
    [_progressLayer removeFromSuperlayer];
    [self.layer addSublayer:_progressLayer];
    
    _progressLabel.frame = self.bounds;
}

- (void)setProgress:(double)progress {
    _progress = progress;
    [self.progressLabel setText:[NSString stringWithFormat:@"%.0f%%",progress*100]];
    [self setNeedsDisplay];
}

#pragma mark - *********** Getter ***********

- (UILabel *)progressLabel{
    if (!_progressLabel){
        UILabel *label = UILabel.new;
        label.font = [UIFont systemFontOfSize:10.f];
        label.textColor = UIColor.greenColor;
        label.textAlignment = NSTextAlignmentCenter;
        _progressLabel = label;
    }
    return _progressLabel;
}


@end
